import { FC, useEffect, useState } from "react";
import { observer, inject } from "mobx-react";
import { Form, Input, Button, message, Modal } from "antd";
import { useNavigate, Link } from "react-router-dom";
import Langbox from "../components/Langbox";
import { ITStore } from "../../store";
import "./index.less";

type TProp = {
  store: ITStore;
};

type Tregparam = {
  account: string;
  password: string;
};

interface ITResetModal extends TProp {
  isShow: boolean;
  close: () => void;
}

const layout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 18 },
};

const pwdFormLayout = {
  default: {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
  },
  next: {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
  },
};

const tailLayout = {
  wrapperCol: { offset: 5, span: 18 },
};

type TResetForm = {
  account?: string;
  email?: string;
  password?: string;
  confirmpassword?: string;
};

// 找回密码弹窗
const ResetPwdModal: FC<ITResetModal | any> = inject("store")(
  observer(({ store, isShow, close }: ITResetModal) => {
    const {
      userStore: { checkAccount, changePassword },
      languageStore: { lang },
    } = store;

    const [form] = Form.useForm();

    const [submitLoading, setSubmitLoading] = useState<boolean>(false);

    const [accountId, setAccountId] = useState<string>("");

    const [showPwdform, setShowPwdform] = useState<boolean>(false);

    const [formLayout, setFormLayout] = useState<any>(pwdFormLayout.default);

    const closeModal = () => {
      setAccountId("");
      setShowPwdform(false);
      setSubmitLoading(false);
      setFormLayout(pwdFormLayout.default);
      close();
    };

    const onFinish = async (values: TResetForm) => {
      if (!showPwdform) {
        setSubmitLoading(true);
        const res: any = await checkAccount(values);
        setSubmitLoading(false);
        if (!res.msg) {
          setFormLayout(pwdFormLayout.next);
          setAccountId(res.id);
          setShowPwdform(true);
        } else {
          message.error(lang["langcheckaccounterr"]);
        }
      } else {
        const { confirmpassword, password } = values;
        if (confirmpassword !== password) {
          message.error(lang["langpwdnotsame"]);
        } else {
          setSubmitLoading(true);
          const res: any = await changePassword({
            password,
            id: accountId,
          });
          setSubmitLoading(false);
          if(!res){
            message.success(lang["langmodifysuccess"]);
            closeModal();
          } else {
            message.error(lang["langfailmodify"]);
          }
        }
      }
    };

    return (
      <Modal
        title={""}
        open={isShow}
        destroyOnClose={true}
        closable={false}
        onOk={() => {
          form.submit();
        }}
        confirmLoading={submitLoading}
        onCancel={closeModal}
      >
        <Form
          {...formLayout}
          form={form}
          onFinish={onFinish}
          style={{ width: "480px", padding: "20px 0 0 20px" }}
        >
          {!showPwdform && (
            <Form.Item
              label={lang["langaccount"]}
              name="account"
              rules={[{ required: true }]}
            >
              <Input />
            </Form.Item>
          )}
          {!showPwdform && (
            <Form.Item
              label={lang["langemail"]}
              name="email"
              rules={[{ required: true, type: "email" }]}
              extra={lang["langrepwdemail"]}
            >
              <Input />
            </Form.Item>
          )}
          {showPwdform && (
            <Form.Item
              label={lang["langpassword"]}
              name="password"
              rules={[{ required: true, min: 6 }]}
            >
              <Input.Password />
            </Form.Item>
          )}
          {showPwdform && (
            <Form.Item
              label={lang["langcnfpwd"]}
              name="confirmpassword"
              rules={[{ required: true, min: 6 }]}
            >
              <Input.Password />
            </Form.Item>
          )}
        </Form>
      </Modal>
    );
  })
);

const Login: FC<TProp | any> = ({ store }: TProp): JSX.Element => {
  const {
    userStore: { loginUser },
    languageStore: { lang, getAllLanguage },
  } = store;
  const [form] = Form.useForm();
  const navigate = useNavigate();

  const [bgIndex, setBgIndex] = useState(0);

  const [showRestModal, setShowRestModal] = useState<boolean>(false);

  useEffect(() => {
    getAllLanguage(false);
    let num = Math.floor(Math.random() * 4);
    setBgIndex(num);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const onFinish = async (values: Tregparam) => {
    const result = await loginUser(values);
    if (!result) {
      navigate("/designer");
    } else {
      // 登录失败提示
      const { msg } = result;
      if (msg === "duplicate") {
        message.error(lang["langregerror"]);
      }
      form.resetFields();
    }
  };

  const closeResetModal = () => setShowRestModal(false);

  return (
    <>
      <div className="loginbody">
        <div className="logintitle">
          Wecome to ZBS Chemical Synthesis Protocol Designer
        </div>
        <div className="logincnt">
          <div className={`topbg bg${bgIndex}`}>
            <div className="title">{lang["langlogin"]}</div>
          </div>
          <Form
            {...layout}
            form={form}
            onFinish={onFinish}
            style={{ width: "480px", padding: "40px 0 0 20px" }}
          >
            <Form.Item
              label={lang["langaccount"]}
              name="account"
              rules={[{ required: true }]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label={lang["langpassword"]}
              name="password"
              rules={[{ required: true }]}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item {...tailLayout}>
              <Button
                loading={false}
                type="primary"
                htmlType="submit"
                style={{ width: "100%" }}
              >
                {lang["langlogin"]}
              </Button>
            </Form.Item>
          </Form>
          <div className="reg">
            <Link
              to=""
              style={{ float: "left" }}
              onClick={() => {
                setShowRestModal(true);
              }}
            >
              {lang["langforgetpwd"]}
            </Link>
            <Link to="/register">{lang["langregister"]}</Link>
          </div>
        </div>
        <div className="lang">
          <Langbox />
        </div>
      </div>
      <ResetPwdModal isShow={showRestModal} close={closeResetModal} />
    </>
  );
};

export default inject("store")(observer(Login));
